python获取字典中的values 您所在的位置:网站首页 python 字典 values python获取字典中的values

python获取字典中的values

#python获取字典中的values| 来源: 网络整理| 查看: 265

1586010002-jmsa.png

How do i get key of index in dictionary?

For example like:

i = {'a': 0, 'b': 1, 'c': 2}

so if i want to get key of i[0], it will return 'a'

解决方案

You could do something like this:

i={'foo':'bar', 'baz':'huh?'}

keys=i.keys() #in python 3, you'll need `list(i.keys())`

values=i.values()

print keys[values.index("bar")] #'foo'

However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.

As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.

Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:

d={'i':1, 'j':1}

In that case, it is impossible to know whether you want i or j and in fact no answer here will be able to tell you which ('i' or 'j') will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有